import { Component, OnInit, Output, EventEmitter, Input, ViewChild } from '@angular/core';
import { AddVMSService } from './add-vms.service';
import { Subject, Subscription, fromEvent } from 'rxjs';
import { debounceTime, distinctUntilChanged, map, takeUntil, concatAll, filter, tap } from 'rxjs/operators';
import { graphic } from 'echarts';
import { DisseminationService } from './../../dissemination-management.service';
import { PublicService } from 'app/public/public.service';
import { ToolsService, NotificationService } from 'app/shared/service';
import { VmsMessageInfoComponent } from './vms-message-info/vms-message-info.component';
const domtoimage = require('dom-to-image');
@Component({
    selector: 'itmp-add-vms',
    templateUrl: './add-vms.component.html',
    styleUrls: ['./add-vms.component.css']
})
export class AddVmsComponent implements OnInit {
    @ViewChild(VmsMessageInfoComponent) msgInfo: VmsMessageInfoComponent;
    mousedownSubject = new Subject<any>();
    @Output() closeModal = new EventEmitter();
    @Input() selectData: any;
    @Input() tabTitle: string;
    isLoading = false;
    constructor(
        private addService: AddVMSService,
        private diss: DisseminationService,
        private tools: ToolsService,
        private pub: PublicService,
        private msg: NotificationService
    ) {}

    ngOnInit() {
        // this.drag();
    }
    cancel() {
        this.closeModal.emit();
    }
    // dom转换成图片
    domtoimage(el, length) {
        el.style.border = 'none'; // 去除边框
        el.style.transform = 'scale(1)';
        this.addService.setShowPage(length - 1);
        setTimeout(() => {
            domtoimage
                .toJpeg(el, { cacheBust: true, quality: 1 })
                .then(dataUrl => {
                    this.addService.imgs[this.addService.showPage] = dataUrl.split(',')[1];
                    // const params = {
                    //     strBase64: dataUrl.split(',')[1],
                    //     graphicName: 'LibMsg_' + this.addService.displayMessage.msgId + '_' + length + '.png'
                    // };
                    // this.pub.uploadImgByBase64(params).subscribe(res => {
                    //     this.addService.imgs[this.addService.showPage] = res.data;
                    length--;
                    if (length > 0) {
                        this.domtoimage(el, length);
                    } else {
                        this.saveTo();
                        el.style.transform = 'scale(2)';
                    }
                    // });
                })
                .catch(function(error) {
                    console.error('oops, something went wrong!', error);
                });
        }, 200);
    }

    // 判断是否满足条件
    checked() {
        const { category, templatePages } = this.addService.displayMessage;
        if (!category.categoryId) {
            return false;
        }
        let isOk = true;
        templatePages.forEach(p => {
            if ((p.templateGraphics || []).length !== (p.graphics || []).length) {
                isOk = false;
            }
        });
        return isOk;
    }

    save() {
        this.isLoading = true;
        const { category, templatePages } = this.addService.displayMessage;
        if (!this.checked()) {
            this.msg.notify({ type: 'warning', path: 'DisseminationManagement.MessageLibrary.create_notify' });
            this.isLoading = false;
            return;
        }
        category.categoryId = this.msgInfo.categoryId;
        this.addService.displayMessage.messageName = this.msgInfo.messageName;

        this.addService.imgs = [];
        this.domtoimage(document.getElementById('viewpoint'), templatePages.length);
    }
    saveTo() {
        let confirm = false;
        const message = this.addService.displayMessage;
        const graphics = [],
            texts = [];
        const { contentStyleList } = this.msgInfo;
        message.templatePages.forEach((item, iOut) => {
            if (item.templateGraphics) {
                item.templateGraphics.forEach((gra, iIn) => {
                    graphics.push({
                        graphicAreaX: gra.graphicAreaX,
                        graphicAreaY: gra.graphicAreaY,
                        graphicSeq: iIn + 1,
                        messageId: message.msgId,
                        pageSeq: iOut + 1,
                        vmsGraphic: item.graphics[iIn] ? item.graphics[iIn].vmsGraphic : null
                    });
                });
            }
            (item.templateTexts || []).forEach((text, iIn) => {
                texts.push({
                    charSpacing: contentStyleList[iOut][iIn]['style']['letter-spacing'],
                    font: contentStyleList[iOut][iIn]['style']['font-size'],
                    foreColor: contentStyleList[iOut][iIn]['style']['color'],
                    textAreaX: text.textAreaX,
                    textAreaY: text.textAreaY,
                    // width: text.width,
                    // height: text.height,
                    messageId: message.msgId,
                    pageSeq: iOut + 1,
                    text: contentStyleList[iOut][iIn] ? contentStyleList[iOut][iIn].text : null,
                    textSeq: iIn + 1,
                    textimageUrl: null
                });
            });
            // templateId.push({
            //     templateId: item.templateId,
            //     pageSeq: iOut + 1
            // });
        });
        const params = {
            categoryId: message.category.categoryId,
            graphics,
            messageDisplayId: message.msgDisplayId,
            messageId: message.msgId,
            templateId: message.templateId,
            messageName: this.msgInfo.messageName,
            texts,
            strBase64List: this.addService.imgs
        };
        message.templatePages.forEach(item => {
            if (item.templateGraphics) {
                if (item.templateGraphics.length > graphics.length) {
                    confirm = true;
                    return;
                }
            }
            if (item.templateTexts) {
                if (item.templateTexts.length > texts.length) {
                    confirm = true;
                    return;
                }
            }
            texts.forEach(text => {
                if (!text.text) {
                    confirm = true;
                    return;
                }
            });
        });
        if (confirm) {
            this.msg.notify({ type: 'warning', path: 'DisseminationManagement.MessageLibrary.create_notify' });
            this.isLoading = false;
            return;
        }

        const isPlainText = ((message.templatePages && message.templatePages[0] && message.templatePages[0].templateGraphics) || []).length
            ? false
            : true;
        const addApiStr = isPlainText ? 'createMessageLibrary' : 'createMessageLibrary';
        const updateApiStr = isPlainText ? 'updateMessageLibrary' : 'updateMessageLibrary';

        this.diss[this.tabTitle === 'Add' ? addApiStr : updateApiStr](params).subscribe(
            res => {
                if (res['messagecode'] === '000000') {
                    this.isLoading = false;
                    setTimeout(() => {
                        this.closeModal.emit();
                    }, 200);
                } else if (res['messagecode'] === '900101') {
                    this.msg.notify({ type: 'warning', path: 'DisseminationManagement.MessageLibrary.datacollide' });
                    this.isLoading = false;
                } else if (res['messagecode'] === '999999') {
                    this.isLoading = false;
                    this.closeModal.emit();
                    this.msg.notify({ type: 'warning', path: 'DisseminationManagement.MessageLibrary.failedRequest' });
                }
            },
            err => {
                console.warn(err);
                this.isLoading = false;
            }
        );
    }
    // 删除之前的图片
    deleteOriginImg() {
        this.selectData.url.split(',').forEach(item => {
            this.diss.deleteOriginImg(item).subscribe();
        });
    }
    preview() {
        this.closeModal.emit();
    }

    // 绑定事件
    mousedownHandle({ data, e }) {
        this.addService.setGraphics(data);
        this.mousedownSubject.next(e);
    }
    // 拖拽
    // drag() {
    //     const drag = document.getElementById('drag');
    //     let dragImg = null;
    //     const mouseDown = fromEvent(document, 'mousedown');
    //     const mouseUp = fromEvent(document, 'mouseup');
    //     const mouseMove = fromEvent(document, 'mousemove');
    //     const validValue = (value, max, min) => {
    //         return Math.min(Math.max(value, min), max);
    //     };
    //     this.mousedownSubject.asObservable().pipe(
    //         tap(e => {
    //             dragImg = document.getElementById('dragImg');
    //             dragImg.style.opacity = '1';
    //             dragImg.style.left = e.clientX - 50 + 'px';
    //             dragImg.style.top = e.clientY - 50 + 'px';
    //         }),
    //         map(e => {
    //             return mouseMove.pipe(
    //                 takeUntil(mouseUp.pipe(
    //                     tap(event => {
    //                         const VMSboardContainer = document.getElementById('VMSboardContainer');
    //                         const contentRight = document.getElementById('contentRight');
    //                         // 拼个位置
    //                         const left = contentRight.offsetLeft + VMSboardContainer.offsetLeft + 320;
    //                         const top = contentRight.offsetTop + VMSboardContainer.offsetTop + 120;
    //                         const bottom = top + VMSboardContainer.clientHeight;
    //                         const right = left + VMSboardContainer.clientWidth;
    //                         if (event.clientX >= left && event.clientX <= right && event.clientY >= top && event.clientY <= bottom) {
    //                             if (this.addService.showPage === 'page1') {
    //                                 this.addService.displayMessage.page1.push(this.addService.selectGraphics.Icon);
    //                             } else {
    //                                 this.addService.displayMessage.page2.push(this.addService.selectGraphics.Icon);
    //                             }
    //                         }
    //                         dragImg.style.opacity = '0';
    //                         dragImg.style.left = -1000 + 'px';
    //                         dragImg.style.top = -1000 + 'px';
    //                     })
    //                 ))
    //             );
    //         }),
    //         concatAll(),
    //         map(e => {
    //             return {
    //                 x: validValue(e.clientX - 50, window.innerWidth - 100, 320),
    //                 y: validValue(e.clientY - 50, window.innerWidth - 100, 120)
    //             };
    //         })
    //     ).subscribe(res => {
    //         dragImg.style.left = res.x + 'px';
    //         dragImg.style.top = res.y + 'px';
    //     });
    // }
}
